<?php
/**
 * 注意：本内容仅限于博也公司内部传阅,禁止外泄以及用于其他的商业目的
 * @author    hebidu<346551990@qq.com>
 * @copyright 2017 www.itboye.com Boye Inc. All rights reserved.
 * @link      http://www.itboye.com/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 * Revision History Version
 ********1.0.0********************
 * file created @ 2017-10-31 13:51
 *********************************
 ********1.0.1********************
 *
 *********************************
 */

namespace app\src\userconfig\action;

use app\src\base\helper\ResultHelper;
use app\src\userconfig\logic\UserPhoneConfigLogic;

class UserPhoneConfigLangAction
{
    const DEFAULT_LANG = 'zh-cn';
    private static $langs = ['zh-cn', 'zh-tw', 'en'];

    /**
     * 获取语言信息
     * @param $uid
     * @param $deviceId
     * @return string
     */
    public function getLang($uid, $deviceId)
    {
        $logic = new UserPhoneConfigLogic();
        $map = ['uid' => $uid, 'device_id' => $deviceId];
        $result = $logic->getInfo($map);
        if ($result['status'] && is_array($result['info'])) {
            $info = $result['info'];
            $lang = (array_key_exists('lang', $info) && in_array($info['lang'], self::$langs)) ? $info['lang'] : UserPhoneConfigLangAction::DEFAULT_LANG;
            return $lang;
        }

        return UserPhoneConfigLangAction::DEFAULT_LANG;
    }

    /**
     * 设置语言参数
     * @param $uid
     * @param $deviceId
     * @param string $lang
     * @return array|string
     */
    public function update($uid, $deviceId = '', $lang = 'zh-cn')
    {
        if (in_array($lang, self::$langs)) {
            $logic = new UserPhoneConfigLogic();
            $map = ['uid' => $uid];
            if (!empty($deviceId)) {
                $map['device_id'] = $deviceId;
            }
            $result = $logic->getInfo($map);
            if ($result['status']) {
                if (empty($result['info'])) {
                    // 插入
                    $entity = $map;
                    $entity['lang'] = $lang;
                    $result = $logic->add($entity);
                } elseif (is_array($result['info'])) {
                    // 更新
                    $result = $logic->save($map, ['lang' => $lang]);
                }
            }

            return $result;
        }

        return ResultHelper::error(lang('err_lang_not_support'));
    }

}